package com.tarena.lbs.basic.web.service.impl;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.dao.repository.AdminRepository;
import com.tarena.lbs.basic.web.service.AdminService;
import com.tarena.lbs.common.basic.converter.AdminConverter;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.bo.AdminBO;
import com.tarena.lbs.pojo.basic.dos.AdminDO;
import com.tarena.lbs.pojo.basic.param.AdminParam;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private AdminConverter adminConverter;

    @Override
    public AdminBO adminDetail() throws BusinessException {
        //1.拿到登录用户的Id
        Integer userId = getLoginUserId();
        //2.调用Repository层查询数据(在Repository做非空判断)
        AdminBO adminBO = adminRepository.getAdminById(userId);
        log.debug("adminBO出参:{}",adminBO);
        //3.返回数据
        return adminBO;
    }

    @Override
    public BasePageList<AdminBO> adminList(AdminQuery query) {
        return adminRepository.adminList(query);
    }

    @Override
    public void addAdminObj(AdminParam adminParam) throws BusinessException {
        log.info("当前新增商家账号入参:{}",adminParam);
        AdminBO adminBO = adminConverter.param2BO(adminParam);
        adminBO.setCreateTime(new Date());
        log.debug("当前新增商家账号adminParam转化为adminBO:{}",adminBO);
        //为保证幂等性查询手机号是否已经存在
        long total=adminRepository.countAdminByPhone(adminBO.getAccountPhone());
        if (total > 0) {
            throw new BusinessException("104","手机号已存在");
        }
        adminRepository.save(adminBO);
    }

    private Integer getLoginUserId() throws BusinessException{
        //1.使用threadLocal获取线程中存储的User数据
        UserPrinciple userInfo = LbsSecurityContenxt.getLoginToken();
        log.debug("通过ThreadLocal获取线程中存储的User数据:{}",userInfo);
        //2.验证非空,获取Id信息返回
        if (ObjectUtils.isEmpty(userInfo)){
            throw new BusinessException("102","登录用户数据不存在");
        }
        return userInfo.getId();
    }
}
